//
//  LCGameTaskViewController.m
//  lechuang
//
//  Created by Mr_hi on 2023/3/31.
//  Copyright © 2023 Mooyi. All rights reserved.
//

#import "LCGameTaskViewController.h"
#import "LCTaskService.h"
#import "LCTaskTableViewCell.h"

#import "XWXAllXieYiController.h"

#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import <DyTaskSdk/DyAdApi.h>

@interface LCGameTaskViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (assign, nonatomic)NSInteger page;

@property (strong, nonatomic)NSMutableArray * dataArr;

@property (nonatomic, assign) BOOL canScroll;

@end

@implementation LCGameTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getIdfa];
    [self configUI];
    [self setTableViewRefresh];
    [self getUnionData];
}

- (void)getIdfa {
    if (@available(iOS 14, *)) {
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
                NSLog(@"%@",idfa);
            } else {
                NSLog(@"请在设置-隐私-Tracking中允许App请求跟踪");
            }
        }];
    } else {
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            NSString *idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            NSLog(@"%@",idfa);
        } else {
            NSLog(@"请在设置-隐私-广告中打开广告跟踪功能");
        }
    }
}

-(void)configUI {
    self.canScroll = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskPageControllerGoTop:) name:LCTaskPageControllerGoTopNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskPageControllerLeaveTop:) name:LCTaskPageControllerLeaveTopNoti object:nil];
}

-(void)taskPageControllerGoTop:(NSNotification *)noti {
    self.canScroll = YES;
}

-(void)taskPageControllerLeaveTop:(NSNotification *)noti {
    self.canScroll = NO;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.canScroll) {
        CGFloat offsetY = scrollView.contentOffset.y;
        if (offsetY <= 0) {
            [self.tableView setContentOffset:CGPointZero];
            [[NSNotificationCenter defaultCenter] postNotificationName:LCTaskPageControllerLeaveTopNoti object:@(YES)];
        }
    } else {
        [self.tableView setContentOffset:CGPointZero];
    }
}

-(void)setTableViewRefresh {
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        [self getTaskListDataWithPage:1];
    }];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        [self getTaskListDataWithPage:self.page];
    }];
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    
    self.tableView.ly_emptyView = [LCEmptyView emptyViewWithImageStr:nil titleStr:nil detailStr:@"暂无数据"];
}

-(void)getUnionData {
    [LCTaskService getUnionDataWithBlock:^(BOOL isSuccess, NSArray<LCUnionModel *> *list) {
        if (isSuccess) {
            for (LCUnionModel * unionM in list) {
                if ([unionM.unionmodel isEqualToString:@"多游"]) {
                    self.unionModel = unionM;
                    [DyAdApi registerWithMediaId:self.unionModel.config.iosappid appKey:self.unionModel.config.iosappsecret];
                }
            }
            [self getTaskListDataWithPage:1];
        }
    }];
}

- (void)getTaskListDataWithPage:(NSInteger)page {
    [LCTaskService getGameTaskListWithAppId:self.unionModel.config.iosappid Key:self.unionModel.config.iosappsecret PageNum:page Block:^(BOOL isSuccess, NSArray<LCGameTaskModel *> *list) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (isSuccess) {
            if (page == 1) {
                [self.dataArr removeAllObjects];
            }
            [self.dataArr addObjectsFromArray:list];
            if (list.count < 10) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        } else {
            if (self.page != 1) {
                self.page--;
            }
        }
    }];
}

-(NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 92;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LCGameTaskTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LCGameTaskTableViewCell"];
    cell.task = self.dataArr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LCGameTaskModel * task = self.dataArr[indexPath.row];
//    NSString * appId = self.unionModel.config.iosappid;
//    NSString * secretKey = self.unionModel.config.iosappsecret;
    NSString * userId = kFORMAT(@"%@",LCUserDefGet(Userid));
    
//    NSMutableDictionary * param = [NSMutableDictionary dictionary];
//    param[@"media_id"] = appId;
//    param[@"user_id"] = userId;
//    param[@"device_type"] = @"1";
    
//    NSMutableArray * paramStrArr = [LCFunction  keyVauleArrWithDictionary:param].mutableCopy;
//    [paramStrArr addObject:[NSString stringWithFormat:@"key=%@",secretKey]];
//    NSString * paramStr = [paramStrArr componentsJoinedByString:@"&"];
//    NSString * sign = [[LCFunction ns_md5:paramStr] lowercaseString];
//
//    NSLog(@"%@",GameTaskDetailWeb(kFORMAT(@"%@",@(task.advert_id)) , appId, userId, @"1", sign));
    
    [DyAdApi presentDetailViewController:self.parentVC userId:userId advertId:kFORMAT(@"%@",@(task.advert_id))];
    
//    XWXAllXieYiController *webVC = [XWXAllXieYiController new];
//    webVC.tileStr = task.title;
//    webVC.urlStr = GameTaskDetailWeb(kFORMAT(@"%@",@(task.advert_id)) , appId, userId, @"1", sign);
//    webVC.isPushFrom = YES;
//    webVC.hidesBottomBarWhenPushed = YES;
//    [self.parentVC.navigationController pushViewController:webVC animated:YES];
}


@end
